package com.example.woke;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.data.Datas_event2;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.apache.http.cookie.Cookie;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class LoadActivity extends Activity {

	private EditText mEphone;
	private EditText mEpsw;
	private TextView mTok;
	private Intent intent;
	private Intentnet net;
	private SharedPreferences sharep;
	private MyApp application;
	private boolean isresutlr = false;//

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_load);

		sharep = getSharedPreferences ("loaduser", Context.MODE_PRIVATE);
		application = (MyApp) getApplication ();
		intent = getIntent ();
		net = new Intentnet ();
		intview ();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult (requestCode, resultCode, data);
		if (requestCode == 659) {
			if (resultCode == 656) {
				ArrayList<String> result = data.getStringArrayListExtra ("result");
				mEphone.setText (result.get (0));
				mEpsw.setText (result.get (1));
			}
		}
	}

	@Override
	protected void onStop() {
		super.onStop ();
		if (isresutlr == false) {
			Datas_event2 data = new Datas_event2 ();
			data.str1 = "0";
			EventBus.getDefault ().post (data);
		}
	}

	/**
	 * ��ȡ��׼ Cookie
	 */
	private List<Cookie> getCookieText() {
		PersistentCookieStore myCookieStore = new PersistentCookieStore (LoadActivity.this);
		List<Cookie> cookies = myCookieStore.getCookies ();
//	       Log.e("cookies.size() = " ,"  "+ cookies.size());  
//	       Log.e("cookies.size() = " ,"  "+ cookies);  
		return cookies;
	}

	private void intview() {

		final Intentnet net = new Intentnet ();

		mEphone = (EditText) findViewById (R.id.avload_edit_phone);
		mEpsw = (EditText) findViewById (R.id.avload_edit_psw);
		mTok = (TextView) findViewById (R.id.avload_text_ok);
		String name = sharep.getString ("name", "");
		String password = sharep.getString ("password", "");
		if (! name.equals ("") && ! password.equals ("")) {
			mEphone.setText (name);
			mEpsw.setText (password);
		}

		mTok.setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				String phone = mEphone.getText ().toString ().trim ();
				String psw = mEpsw.getText ().toString ().trim ();
				if (phone.equals ("") || null == phone) {
					Toast.makeText (LoadActivity.this, "手机号码不能为空！", Toast.LENGTH_SHORT).show ();
				} else if (net.isMobile (phone) == false) {
					Toast.makeText (LoadActivity.this, "非法的手机号", Toast.LENGTH_SHORT).show ();
				} else if (net.isMobile (phone) == false) {
					Toast.makeText (LoadActivity.this, "非法的手机号码！", Toast.LENGTH_SHORT).show ();
				} else if (psw.equals ("") || null == psw) {
					Toast.makeText (LoadActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show ();
				} else {
					if (net.isNetworkConnected (LoadActivity.this) == true) {
//						mBar.setVisibility(View.VISIBLE);
						loadphone (phone, psw);
					} else {
						Toast.makeText (LoadActivity.this, "请检查您的网络！", Toast.LENGTH_SHORT).show ();
					}
				}
			}
		});

		findViewById (R.id.avload_text_forget).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent (LoadActivity.this, ForgetpswActivity.class);
				startActivity (intent);
			}
		});

		findViewById (R.id.avload_image_back).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				finish ();
			}
		});

		findViewById (R.id.avload_text_toRegister).setOnClickListener (new OnClickListener () {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent (LoadActivity.this, RegisterActivity.class);
				startActivityForResult (intent, 659);
			}
		});
	}

	private void loadphone(final String phone, final String psw) {
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (LoadActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		Log.e("login","---"+ JPushInterface.getRegistrationID(this));
		params.put ("g", "api");
		params.put ("m", "user");
		params.put ("a", "login");
		params.put ("username", phone);
		params.put ("password", psw);
		params.put ("registerid", JPushInterface.getRegistrationID(this));
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("登录dd数据", "" + response);
				getCookieText ();
				try {
					String flag = response.getString ("flag");
					String info = response.getString ("info");
					if (flag.equals ("success")) {
						JSONObject jsonObject = response.getJSONObject ("data");
						String string = jsonObject.getString ("data");
						Gson gson=new Gson ();
//						Datas_load datas_load = JSONArray.parseObject (string, Datas_load.class);
						Datas_load datas_load = gson.fromJson (string,Datas_load.class);
						application.setDatas_load (datas_load);
						Toast.makeText (LoadActivity.this, "登录成功！", Toast.LENGTH_SHORT).show ();
						Datas_event2 data = new Datas_event2 ();
						EventBus.getDefault ().post (data);
						Editor edit = sharep.edit ();
						edit.putString ("name", phone);
						edit.putString ("password", psw);
						edit.putString ("load", "load");
						edit.commit ();
						isresutlr = true;
						intent.putExtra ("phone", phone);
						setResult (658, intent);
						finish ();
					} else {
						Toast.makeText (LoadActivity.this, "登录失败！" + info, Toast.LENGTH_SHORT)
								.show ();
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onStart() {
				super.onStart ();
				mTok.setBackgroundDrawable (getResources ().getDrawable (
						R.drawable.rect_lightgray));
				mTok.setClickable (false);

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Toast.makeText (LoadActivity.this, "登录失败！服务器未响应", Toast.LENGTH_SHORT).show ();
				Log.e ("response", "失败" + responseString);
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				Log.e ("d", "d");
				mTok.setBackgroundDrawable (getResources ().getDrawable (
						R.drawable.rect_lightred));
				mTok.setClickable (true);
//				mFrame.setVisibility(View.GONE);
			}
		});
	}

}
